package com.fourpigeon.utils;

import cn.hutool.core.bean.BeanUtil;
import com.fourpigeon.domain.UserDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static com.fourpigeon.utils.RedisConstants.LOGIN_USER_TOKEN_KEY;

/**
 * 刷新SessionId的拦截器
 */
public class RefreshUserTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;
    private Random random = new Random();

    public RefreshUserTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 由于存在两个拦截器，即使这里放行了，后面的LoginInterceptor中如果没有放行，同样会被拦截
     * @param request current HTTP request
     * @param response current HTTP response
     * @param handler chosen handler to execute, for type and/or instance evaluation
     * @return 是否放行
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头的token
        String token = request.getHeader("authorization");
        if (token == null) {
            System.out.println("无token");
            return true;
        }
        System.out.println("token = "+token);
        //获取用户
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(LOGIN_USER_TOKEN_KEY + token);
        //判断用户是否存在
        if (userMap.isEmpty()) {
            System.out.println("用户Map为空");
            return true;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        System.out.println(userDTO);
        UserHolder.saveUser(userDTO);
        //浮动有效期
        stringRedisTemplate.expire(LOGIN_USER_TOKEN_KEY+token,10060+random.nextInt(20), TimeUnit.MINUTES);
        return true;
    }
}
